<template>
	<div class="container">
		<el-page-header @back="goBack" content="小哥车辆管理"></el-page-header>

		<el-row type="flex" justify="space-between" class="nav-bar">
			<el-col :span="3">
				<el-button type="primary" icon="el-icon-plus" plain @click="dialogVisiblecar = true">新建车辆</el-button>
			</el-col>
			<el-col class="text-right">
				<el-form :inline="true" label-width="auto" class="nav-bar-form">
					<!-- <el-form-item label="小哥名称">
						<el-select v-model="userid" filterable placeholder="请选择">
							<el-option v-for="item in useList" :key="item.value" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
					</el-form-item> -->
					<el-form-item label="车辆类型">
						<el-select v-model="carid" placeholder="请选择" @change="getList">
							<el-option v-for="item in carList" :key="item.value" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-input placeholder="关键词搜索" v-model="key" clearable prefix-icon="el-icon-search"
							@clear="getList"></el-input>
					</el-form-item>

					<el-form-item>
						<el-button type="primary" @click="getList">查询</el-button>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>
		<el-table :data="tableData" style="width: 100%" stripe>
			<el-table-column fixed type="index" label="序号" width="50">
                </el-table-column>
			<el-table-column fixed prop="peoplevehiclepic">
				<template slot-scope="scope">
					<div>
						<el-image style="width: 120px; height: 100px" :src="fileURL + scope.row.vehiclepic"
							fit="cover"></el-image>
					</div>
				</template>
			</el-table-column>
			<el-table-column fixed prop="licenseplate" label="车牌号">
			</el-table-column>
			<!-- <el-table-column prop="vehiclestate" label="车辆使用状态">
			</el-table-column>
			<el-table-column label="最后车辆使用小哥">
				<template slot-scope="scope">
					<span>{{ scope.row.brothername }}</span>
				</template>
			</el-table-column> -->
			<el-table-column prop="type" label="车型">
				<template slot-scope="scope">
					<span>{{ scope.row.type.name }}</span>
				</template>
			</el-table-column>

			<el-table-column prop="starttime" label="车辆开始使用时间">
				<template slot-scope="scope">
					<span v-if="scope.row.starttime">{{ scope.row.starttime }}</span>
					<span v-if="!scope.row.starttime">未使用</span>
				</template>
			</el-table-column>
			<el-table-column prop="load" label="载重量（KG）">
			</el-table-column>
			<el-table-column prop="terminalphoneno" label="GPS设备号">
			</el-table-column>
			<el-table-column label="GPS定位">
				<template slot-scope="scope">
					<span @click="getLastLocation(scope.row)">
						{{ scope.row.lastlocation ? scope.row.lastlocation : "点击查看位置" }}
					</span>
				</template>
			</el-table-column>
			<el-table-column prop="terminalopen" label="GPS是否连接">
				<template slot-scope="scope">
					<span>{{ scope.row.terminalopen ? "是" : "否" }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" width="220">
				<template slot-scope="scope">
					<el-button @click="getDetails(scope.row.id)" type="text" size="small">查看</el-button>
					<el-button @click="edit(scope.row.id)" type="text" size="small">编辑</el-button>
					<el-button @click="viewTrajectory(scope.row.id)" type="text" size="small">轨迹</el-button>
					<el-button v-if="scope.row.terminalphoneno == ''" @click="showBindGPS(scope.row)" type="text"
						size="small">绑定GPS</el-button>
					<el-button v-else="" @click="UnbindGPS(scope.row)" type="text" size="small">解绑GPS</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div class="table-pagination">
			<el-pagination background layout="sizes, total, prev, pager, next" :total="total"
				:page-sizes="[10, 50, 100, 200]" :page-size="pageSize" :current-page="page" @current-change="pageChange"
				@size-change="handleSizeChange">
			</el-pagination>
		</div>
		<el-dialog title="查看车辆详情" :visible.sync="dialogVisible" width="1200px">
			<el-descriptions class="margin-top" :column="3" border>
				<el-descriptions-item label="车牌号">
					<span>{{ form.licenseplate }}</span>
				</el-descriptions-item>
				<el-descriptions-item label="车型">
					<span>{{ form.type.name }}</span>
				</el-descriptions-item>
				<el-descriptions-item label="载重量">
					<span>{{ form.load }}KG</span>
				</el-descriptions-item>
				<el-descriptions-item label="行驶证正页">
					<el-image style="width: 120px; height: 100px" :src="fileURL + form.drivinglicensefront" fit="cover"
						:preview-src-list="[fileURL + form.drivinglicensefront]"></el-image>
				</el-descriptions-item>
				<el-descriptions-item label="行驶证副页">
					<el-image style="width: 120px; height: 100px" :src="fileURL + form.drivinglicenseback" fit="cover"
						:preview-src-list="[fileURL + form.drivinglicenseback]"></el-image>
				</el-descriptions-item>
				<el-descriptions-item label="驾驶证正页">
					<el-image style="width: 120px; height: 100px" :src="fileURL + form.driverslicensefront" fit="cover"
						:preview-src-list="[fileURL + form.driverslicensefront]"></el-image>
				</el-descriptions-item>
				<el-descriptions-item label="驾驶证副页">
					<el-image style="width: 120px; height: 100px" :src="fileURL + form.driverslicenseback" fit="cover"
						:preview-src-list="[fileURL + form.driverslicenseback]"></el-image>
				</el-descriptions-item>
				<el-descriptions-item label="车照">
					<el-image style="width: 120px; height: 100px" :src="fileURL + form.vehiclepic" fit="cover"
						:preview-src-list="[fileURL + form.vehiclepic]"></el-image>
				</el-descriptions-item>
				<el-descriptions-item label="人车合影">
					<el-image style="width: 120px; height: 100px" :src="fileURL + form.peoplevehiclepic" fit="cover"
						:preview-src-list="[fileURL + form.peoplevehiclepic]"></el-image>
				</el-descriptions-item>
			</el-descriptions>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">关闭</el-button>
			</span>
		</el-dialog>
		<el-dialog title="绑定车辆GPS" :visible.sync="dialogVisibleBindGPS" width="600px">
			<el-descriptions class="margin-top" :column="1" border>
				<el-descriptions-item label="车牌号">
					<span>{{ form.licenseplate }}</span>
				</el-descriptions-item>
				<el-descriptions-item label="GPS设备号">
					<el-input v-model="form.terminalphoneno" placeholder="请输入GPS设备号" />
				</el-descriptions-item>
			</el-descriptions>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisibleBindGPS = false">关闭</el-button>
				<el-button type="primary" @click="BindGPS">确定</el-button>
			</span>
		</el-dialog>
		<el-dialog title="添加车辆" :visible.sync="dialogVisiblecar" width="50%">
			<div>
				<el-form ref="carform" :model="carform" :rules="rules" label-width="130px">
					<el-form-item label="车辆类型" prop="typeid">
						<el-radio-group v-model="carform.typeid" >
							<el-radio :label="item.id" v-for="item in cartype" :key="item.id">{{ item.name }}</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="车牌号码" prop="licenseplate">
						<el-input v-model="carform.licenseplate"></el-input>
					</el-form-item>
					<el-form-item label="载重量(kg)" prop="load">
						<el-input v-model="carform.load"></el-input>
					</el-form-item>
					<!-- 提醒设置 -->
					<el-form-item label="设置保险提醒时间">
						<el-date-picker
							v-model="carform.insurancedate"
							type="datetime"
							placeholder="选择日期时间">
						</el-date-picker>
					</el-form-item>
					<el-form-item label="设置年检提醒日期">
						<el-date-picker
							v-model="carform.inspectiondate"
							type="datetime"
							placeholder="选择日期时间">
						</el-date-picker>
					</el-form-item>
					<el-form-item label="到期短信提醒号码">
						<el-input v-model="carform.telphones" placeholder="请输入手机号，多个手机号用英文逗号(,)分割"></el-input>
						<!-- <el-select 
							v-model="carform.telphones"
							multiple
							filterable
							remote
							reserve-keyword
							placeholder="请输入手机号码搜索"
							:remote-method="remoteMethod"
							:loading="loading">
							<el-option
							v-for="item in options"
							:key="item.value"
							:label="item.label"
							:value="item.value">
							</el-option>
						</el-select> -->
					</el-form-item>
					<el-form-item label="提醒模式">
						<el-checkbox-group v-model="carform.remindtime">
							<el-checkbox label="30" name="remindtime">提前30天提醒</el-checkbox>
							<el-checkbox label="15" name="remindtime">提前15天提醒</el-checkbox>
							<el-checkbox label="7" name="remindtime">提前7天提醒</el-checkbox>
							<el-checkbox label="0" name="remindtime">当天提醒</el-checkbox>
						</el-checkbox-group>
					</el-form-item>
					<!-- 上传真 -->
					<el-form-item label="上传行驶证正页" prop="drivinglicensefront">
						<cropper-upload :zoomScale='[1, 1]' :isCropper="false" @getUpload="carfont" class="avatar-uploader">
							<img v-if="carform.drivinglicensefront" :src="fileURL + carform.drivinglicensefront"
								class="avatar">
							<div class="avatar-uploader-icon" v-else>
								<div><i class="el-icon-plus"></i></div>
								<div class="e-font-14">上传图片</div>
							</div>
						</cropper-upload>
						<div class="tips">建议上传尺寸比例为200*200 </div>
					</el-form-item>
					<el-form-item label="上传行驶证副页" prop="drivinglicenseback">
						<cropper-upload :zoomScale='[1, 1]' :isCropper="false" @getUpload="carback" class="avatar-uploader">
							<img v-if="carform.drivinglicenseback" :src="fileURL + carform.drivinglicenseback"
								class="avatar">
							<div class="avatar-uploader-icon" v-else>
								<div><i class="el-icon-plus"></i></div>
								<div class="e-font-14">上传图片</div>
							</div>
						</cropper-upload>
						<div class="tips">建议上传尺寸比例为200*200 </div>
					</el-form-item>
					<el-form-item label="车辆照片" prop="vehiclepic">
						<cropper-upload :zoomScale='[1, 1]' :isCropper="false" @getUpload="pic" class="avatar-uploader">
							<img v-if="carform.vehiclepic" :src="fileURL + carform.vehiclepic" class="avatar">
							<div class="avatar-uploader-icon" v-else>
								<div><i class="el-icon-plus"></i></div>
								<div class="e-font-14">上传图片</div>
							</div>
						</cropper-upload>
						<div class="tips">建议上传尺寸比例为200*200 </div>
					</el-form-item>
				</el-form>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisiblecar = false">取 消</el-button>
				<el-button type="primary" @click="getcarfrom('carform')">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
export default {
	layout: 'admin',
	head() {
		return {
			title: '小哥车辆管理' 
		}
	},
	data() {
		return {
			rules: {
				typeid: [
					{ required: true, message: '请选择车辆类型', trigger: 'change' },
				],
				licenseplate: [
					{ required: true, message: '请输入车牌号码', trigger: 'blur' },
				],
				load: [
					{ required: true, message: '请输入载重量', trigger: 'blur' },
					{ min: 1, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
				],
				drivinglicensefront: [
					{ required: true, message: '请上传证件', trigger: 'blur' },
				],
				drivinglicenseback: [
					{ required: true, message: '请上传证件', trigger: 'blur' },
				],
				vehiclepic: [
					{ required: true, message: '请上传证件', trigger: 'blur' },
				],
			},
			carform: {
				typeid: 0,
				licenseplate: "",
				load: '',
				drivinglicensefront: '',
				drivinglicenseback: '',
				vehiclepic: '',
				insurancedate: null,
				inspectiondate: null,
				telphones: '',
				remindtime: []
			},//新建车辆表单
			cartype: [],//车辆类型数据
			dialogVisiblecar: false,//添加车辆
			useList: [],
			userid: 0,
			carList: [],
			carid: 0,
			key: '',
			page: 1,
			pageSize: 10,
			loading: false,
			total: 0,
			dialogVisible: false,
			dialogVisibleBindGPS: false,
			tableData: [],
			form: {
				terminalphoneno: '',
				licenseplate: "",
				type: {}
			},
			geocoder: null,
			AMap: null,
			// 可选号码
			options: [{
				value: '选项1',
				label: '黄金糕'
			}, {
				value: '选项2',
				label: '双皮奶'
			}, {
				value: '选项3',
				label: '蚵仔煎'
			}, {
				value: '选项4',
				label: '龙须面'
			}, {
				value: '选项5',
				label: '北京烤鸭'
			}],
		}
	},
	watch: {
		dialogVisiblecar() {
			this.carform = {
				typeid: '',
				licenseplate: "",
				load: '',
				drivinglicensefront: '',
				drivinglicenseback: '',
				vehiclepic: '',
				insurancedate: null,
				inspectiondate: null,
				telphones: '',
				remindtime: []
			}//新建车辆表单
		}
	},
	mounted() {
		this.getList()
		// this.getuselist()
		this.getcarlist()
		this.getListcartype()
		var that = this;
		this.$AMapLoader.load({
			key: this.AMapSetting.key, // 申请好的Web端开发者Key，首次调用 load 时必填
			version: this.AMapSetting.version, // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
			plugins: ['AMap.Geocoder'],
		}).then((AMap) => {
			that.AMap = AMap;
			that.geocoder = new AMap.Geocoder({
				city: "010", //城市设为北京，默认：“全国”
				radius: 1000 //范围，默认：500
			});
		}).catch(e => {
			console.log(e);
		})
	},
	methods: {
		getListcartype() {
			this.$axios.post('/Operator/VehicleType/List', {
				"PageIndex": 1,
				"PageSize": 999,
				// "Key": this.key
			}).then((res) => {
				this.cartype = res.rows;
				// this.total = res.total;
			})
		},
		remoteMethod(query) {
			// 通过号码搜索通知的用户
			if (query !== '') {
				this.loading = true;
				// setTimeout(() => {
				// 	this.loading = false;
				// 	this.options = this.list.filter(item => {
				// 	return item.label.toLowerCase()
				// 		.indexOf(query.toLowerCase()) > -1;
				// 	});
				// }, 200);
			} else {
				this.options = [];
			}
		},
		getcarfrom(formName) {
			this.$refs[formName].validate((valid) => {
          if (valid) {
			this.$axios.post('/Operator/Vehicle/Create', this.carform).then(res => {
				console.log(res)
				this.dialogVisiblecar = false
				this.getList()

			})
          } else {
            console.log('error submit!!');
            return false;
          }
        });
			
		},
		carfont(res, file) {
			console.log(res, file)
			if (file.status === "success") {
				// this.loading = false
				this.carform.drivinglicensefront = res.path
				this.$forceUpdate()
			}
		},
		carback(res, file) {
			console.log(res, file)
			if (file.status === "success") {
				// this.loading = false
				this.carform.drivinglicenseback = res.path
				this.$forceUpdate()
			}
		},
		pic(res, file) {
			console.log(res, file)
			if (file.status === "success") {
				// this.loading = false
				this.carform.vehiclepic = res.path
				this.$forceUpdate()
			}
		},
		getcarlist() {
			this.$axios.post('/Operator/VehicleType/List', {
				"pageIndex": 1,
				"pageSize": 20,
				"offset": 0,
			}).then((res) => {
				console.log(res)
				this.carList = res.rows
				this.carList.unshift({
					name: '全部',
					id: 0
				})
			})
		},
		// getuselist() {
		// 	this.$axios.post('/Select/brotherlist', {
		// 		"pageIndex": 1,
		// 		"pageSize": 20,
		// 		"offset": 0,
		// 	}).then((res) => {
		// 		console.log(res)
		// 		this.useList = res.rows
		// 		this.useList.unshift({
		// 			name: '全部',
		// 			id: 0
		// 		})
		// 	})
		// },
		goBack() {
			this.$router.go(-1)
		},
		getList() {
			this.$axios.post('/Operator/Vehicle/List', {
				"PageIndex": this.page,
				"PageSize": this.pageSize,
				"Key": this.key,
				"brotherid": this.userid,
				"typeid": this.carid
			}).then((res) => {
				res.rows.forEach(row => {
					row.lastlocation = '';
				});
				this.tableData = res.rows;
				this.total = res.total;
			})
		},
		getLastLocation(vehicle) {
			var that = this;
			this.$axios.get('/Operator/Vehicle/LastLocation?id=' + vehicle.id).then((res) => {
				that.AMap.convertFrom(res.lng + ',' + res.lat, 'gps', function (status, result) {
					that.geocoder.getAddress(result.locations[0].lng + ',' + result.locations[0].lat, function (status, result) {
						if (status === 'complete' && result.regeocode) {
							vehicle.lastlocation = res.date + '\r\n' + result.regeocode.formattedAddress;
						} else {
							that.$message.error('根据经纬度查询地址失败');
						}
					});
				});

			});
		},
		UnbindGPS(vehicle) {
			this.$confirm(`是否解绑 “${vehicle.licenseplate}” GPS设备?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$axios.get('/Operator/Vehicle/UnbindGPS?id=' + vehicle.id).then((res) => {
					this.$message.success(res.msg);
					vehicle.terminalphoneno = '';
				})
			});
		},
		showBindGPS(vehicle) {
			this.form.id = vehicle.id;
			this.form.licenseplate = vehicle.licenseplate;
			this.form.terminalphoneno = '';
			this.dialogVisibleBindGPS = true;
		},
		BindGPS() {
			this.$axios.get('/Operator/Vehicle/BindGPS?id=' + this.form.id + '&phoneNo=' + this.form.terminalphoneno).then((res, data) => {
				this.$message.success('绑定成功');
				this.tableData.find(c => c.id == this.form.id).terminalphoneno = res;
				this.dialogVisibleBindGPS = false;
			});
		},
		getDetails(id) {
			// this.dialogVisible = true;
			// this.$axios.get('/pages/vehicle/view?id=' + id).then((res) => {
			// 	this.form = res;
			// })
			this.$router.push('/vehicle/view?id=' + id)
		},
		edit(id){
			this.$router.push('/vehicle/edit?id=' + id)
		},
		viewTrajectory(id) {
			this.$router.push({
				path: '/vehicle/trajectory?id=' + id
			})
		},
		search() {
			this.getList()
		},
		pageChange(e) { // 页码切换事件
			this.page = e;
			this.getList()
		},
		handleSizeChange(val) {
			this.page = 1;
			this.pageSize = val;
			this.getList()
		}
	}
}
</script>

<style lang="scss">
.nav-bar {
	padding: 45px 0 0;
}

.send {
	margin-top: 15px;
	margin-right: 10px;
}

.dialogForm {
	display: flex;
	flex-wrap: wrap;

	.el-form-item {
		width: 50%;
		float: left;

		&.all {
			width: 100%;
		}

		.el-select {
			width: 100%;
		}
	}
}
</style>
